<template>
  <div id="app">
    <transition name="slide-left-fade" mode="out-in">
      <router-view></router-view>
    </transition>
  </div>
</template>

<script>
import api from 'api'
import io from 'socket.io-client'
import alertDevice from 'alert-device'

export default {
  name: 'App',
  components: {
  },
  data () {
    return {
      electricDeviceId: alertDevice.electricId,
      waterDeviceId: alertDevice.waterId
    }
  },
  mounted () {
    this.connect(this.electricDeviceId)
    this.connect(this.waterDeviceId)
  },
  methods: {
    connectDevices () {
      let waterDevices = alertDevice['water']
      let electricDevices = alertDevice['electric']
      if (waterDevices && waterDevices.length) {
        _.forEach(waterDevices, (item) => {
          this.connect(item.id, 'water')
        })
      }
      if (electricDevices && electricDevices.length) {
        _.forEach(electricDevices, (item) => {
          this.connect(item.id, 'water')
        })
      }
    },
    /**
     * 连接socket逻辑
     * @return {[type]} [description]
     */
    connect (deviceId) {
      api.diagnosis.getDeviceToken(deviceId).then((res) => {
        let token = res.data.token
        // 使用https协议
        // socket = io.connect(window.location.protocol + '//' + addr, {'force new connection': true, secure: true})
        // 使用http协议
        io.set('transports', ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']) // for ie10
        let socket = io.connect('http://' + res.data.addr, {'force new connection': true})

        // 连接 socket
        socket.on('connect', () => {
          window.setTimeout(() => {
            socket.emit('trace.logs', {id: deviceId, token: token})
          }, 100)
        })

        // 断开 socket 连接
        socket.on('disconnect', (data) => {
          console.log('disconnect' + data)
        })

        // 输入日志
        socket.on('trace.log', (data) => {
          this.analysis(data) // 解析数据
        })

        // 输出状态
        socket.on('trace.status', (data) => {
          console.log(data)
        })
      }).catch((res) => {
        this.handleError(res)
      })
    },
    /**
     * 解析数据
     * @param  {[type]}  data socket返回的数据
     * @return {Boolean}      [description]
     */
    analysis (data) {
      // 判断是不是当前的设备
      let log = JSON.parse(data.log)
      if (!log.msg || !log.msg.device || !log.msg.device.datapoint || !log.msg.device.datapoint.length) {
        return
      }
      let dp = log.msg.device.datapoint
      if (parseInt(this.waterDeviceId) === data.id) {
        dp.forEach((item) => {
          if (typeof item['27'] === 'number') {
            let val = item['27']
            if (val > 1.65 || val < 1.2) {
              let label = '过高'
              if (val < 1.2) {
                label = '过低'
              }
              // 排水设备告警
              this.$store.dispatch('showAlert', {
                name: '13-14栋消防水泵房',
                message: `管压${label} 当前: ${val}`,
                value: val,
                device: '高区消防栓',
                type: 'water'
              })
            }
          }
        })
      } else if (parseInt(this.electricDeviceId) === data.id) {
        dp.forEach((item) => {
          if (typeof item['107'] === 'number') {
            let val = item['107']
            if (val > 1 || val < 0.9) {
              let label = '过高'
              if (val < 0.9) {
                label = '过低'
              }
              // 电力设备告警
              this.$store.dispatch('showAlert', {
                name: '3栋配电房',
                message: `总功率因素${label} 当前: ${val}`,
                value: val,
                device: '三相电力监控仪',
                type: 'electric'
              })
            }
          }
          if (typeof item['108'] === 'number') {
            let val = item['108']
            if (val > 470 || val < 0) {
              let label = '过高'
              if (val < 0) {
                label = '过低'
              }
              // 电力设备告警
              this.$store.dispatch('showAlert', {
                name: '3栋配电房',
                message: `总功率因素${label} 当前: ${val}`,
                value: val,
                device: '三相电力监控仪',
                type: 'electric'
              })
            }
          }
        })
      }
    },
    requestRestfulData () {
      // 发送消息给vuex,vuex中写了申请api接口(关于统计数据表部分)
      // this.$store.dispatch('updateWaterStatistics')
      // this.$store.dispatch('updateElectricalStatistics')
      // this.$store.dispatch('updatePhoneStatistics')
    }
  }
}
</script>

<style lang="stylus">
@import './assets/stylus/base'

body {
  margin: 0;
}

#app {
  height: 100%;
  min-width: 1000px;
}

.main {
  size: 100%;
}



</style>
